package org.swidgets.base.sinputbox;

import com.google.gwt.user.client.rpc.AsyncCallback;


public class SRegexInputBox extends SInputBox   {

	private final RegExp regEx;
	protected final String message;
	protected static final String NEW_LINE_ONFAILURE = "\n  - ";
	
	public SRegexInputBox(String regEx, String message) {
		super();
		this.regEx = RegExp.create(regEx);
		this.message = message;
	}
	
	public SRegexInputBox(String label, String regEx, String message) {
		super(label);
		this.regEx = RegExp.create(regEx);
		this.message = message;
	}
	
	private boolean isValid() {
		return regEx.test(getText()) && vetoChange();
	}

	protected boolean vetoChange(){
		return true;
	}
	
	protected void onFailure() {
		errorOn(message);
	}

	public void validate(final AsyncCallback callback) {
		errorOff();
		if (!isValid()) {
			onFailure();
			super.validate(callback);
		}
		super.validate(callback);
	}
}
